<template>
  <div class="my-form-parser">
    <parser ref="parser" :key="key" v-if="formConf" :form-conf="formConf" />

    <div class="my-form-view" v-if="model && uploadField && uploadField.length > 0">
      <file-view v-for="(item, index) in uploadField"
                 :key="index"
                 :params="{xtlx: item, relateId: model.id}"
                 :delete-able="!formConf.disabled"
                 title="附件"/>
    </div>
  </div>
</template>
<script>

import Parser from './Parser'
import { deepClone } from '@/util/index'

export default {
  name: 'my-form-parser',
  cnName: '解析-填充表单',
  components: {
    Parser
  },
  props: {
    tableForm: {
      type: Object,
      required: true
    },
    data: Object,
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      key: +new Date(),
      formConf: null,
      model: this.data
    }
  },
  methods: {
    test() {
      this.fillForm( )
    },
    async init() {
      this.parseForm()
      this.fillForm()
    },
    parseForm() {
      const formConf = deepClone(this.tableForm)
      const fields = formConf.fields
      if(this.disabled) {
        formConf.disabled = this.disabled
      }

      let index = 0
      fields.forEach(field => {
        const {__config__, __slot__, __vModel__} = field
        const {tag, dataType, dictType} = __config__
        if(dataType === 'dynamic') {
          // 清空动态数据的选项
          if(field.__slot__ && field.__slot__.options) {
            field.__slot__.options = []
          }
          if(field.options) {
            field.options = []
          }
          this.loadDicts(field, dictType, tag === 'el-cascader' ? 2 : 1).then(_ => {
            index++
            if(index === fields.length ) {
              this.updateForm()
            }
          })
        } else {
          index++
          if(index === fields.length - 1) {
            this.updateForm()
          }
        }
      })
      this.formConf = formConf
    },
    fillForm() {
      if(!this.model || !this.formConf) return
      const fields = this.formConf.fields

      const fillFn = (fields) => {
        fields.forEach(field => {
          if(field.__config__.children && field.__config__.children.length > 0) {
            fillFn(field.__config__.children)
          } else {
            const val = this.model[field.__vModel__]
            if(typeof val === 'undefined' || val === null) return
            field.__config__.defaultValue = val
          }
        })
      }
      fillFn(fields)
     this.updateForm()
    },
    updateForm() {
      // 更新表单
      this.key = +new Date()
    },
    getUploadData() {
      const refs = this.$refs.parser.$refs
      let rtn = []
      Object.keys(refs).forEach(key => {
        // upload开头的ref
        if(key.indexOf('upload') !== -1) {
          const uploads = refs[key].$refs.upload
          uploads.forEach(upload => {
            const list = upload.getData()
            rtn = rtn.concat(list)
          })
        }
      })
      return rtn
    },
    async loadDicts(field, dictType, dictKind) {
      const list = await this.$store.dispatch('loadDictByType', {dictType, dictKind})
      if(field.__config__.tag === 'el-cascader') {
        field.options = list
      } else  {
        field.__slot__.options = list
      }
    },
    submit(cb) {
      return new Promise((resolve, reject) => {
        const ref = this.formConf.formRef
        const model = this.$refs.parser[this.formConf.formModel]
        this.$refs.parser.$refs[ref].validate(ok => {
          cb && cb(ok, model)
        })
      })
    }
  },
  watch: {
    data: {
      handler() {
        this.model = this.data
        this.fillForm()
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    uploadField() {
      if(!this.formConf) return
      const uploadFields = []
      this.formConf.fields.forEach(o => {
        if(o.__config__.tag === 'el-upload') {
          const xtlx = o.xtlx
          if(!uploadFields.includes(xtlx)) {
            uploadFields.push(xtlx)
          }
        }
      })
      return uploadFields
    }
  },
  mounted() {
    this.init()
  }
}
</script>
<style scoped lang="scss">
.my-form-view {

}
</style>
